from django.shortcuts import render

# Create your views here.
from .models import *
from django.shortcuts import render, get_object_or_404
from django.http import *
from django.views.generic import ListView
import time
from django.core.paginator import Paginator
from django.utils import timezone
import random
from django.http import HttpResponseRedirect


class Index(ListView):
    model = Post
    template_name = 'index.html'

    def get_queryset(self):
        return super(Index, self).get_queryset()

    def get_context_data(self, **kwargs):
        dic = super(Index, self).get_context_data()
        page = self.request.GET.get('page')
        classify = self.request.GET.get('classify')
        # 分类处理
        if classify == '1':
            post_list = Post.objects.filter(category__category_name='前端学习')
            dic['classify'] = "前端学习"
        if classify == '2':
            post_list = Post.objects.filter(category__category_name='后端学习')
            dic['classify'] = "后端学习"
        if not classify:
            post_list = Post.objects.all()
            dic['status_code'] = "0"
        #    如果没拿到页数,默认第一页
        p_list = Paginator(post_list, 10)
        if not page:
            page = 1
        post_list = p_list.page(int(page))
        dic['post_list'] = list(reversed(post_list))
        return dic


class Detail(ListView):
    template_name = 'detail.html'
    model = Post

    def get_queryset(self):
        return super(Detail, self).get_queryset()

    def get_context_data(self, **kwargs):
        dic = {}
        post_id = self.request.GET.get('id')
        post = Post.objects.get(pk=post_id)
        post.visitor_num += 1
        post.save()
        dic['post'] = post
        recent_post = Post.objects.all().order_by('create_time')
        count = len(recent_post)
        if count < 7:
            dic['recent_post'] = recent_post[0:len(recent_post)]
        else:
            dic['recent_post'] = recent_post[0:7]
        try:
            prev_post = Post.objects.filter(id__lt=post_id).order_by('-id')[0]
            dic['prev_post'] = prev_post
        except Exception:
            prev_post = None
        try:
            next_post = Post.objects.filter(id__gt=post_id).order_by('-id')[0]
            dic['next_post'] = next_post

        except Exception:
            next_post = None

        return dic
